<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/29
 * Time: 14:14
 */

namespace Home\Controller;


use Common\Utils\Constants;
use Common\Utils\HttpUtils;
use Common\Utils\WeChatUtils;
use Home\Logic\PayLogic;
use Home\Logic\UserLogic;
use Think\Controller;

class RechargeController extends Controller
{
    function __construct()
    {
        parent::__construct();
        $this->assign('system_name',$this->getSystemName());
    }

    protected function getSystemName(){
        $system_name = M('Config')->where(array('name'=>Constants::CONFIG_SYSTEM_NAME))->getField('value');
        return $system_name.'';
    }

    public function index(){
        $this->display();
    }

//    public function new_index(){
//        $APPID = C('APPID');
//        $APPSECRET = C('APPSECRET');
//        $TOKEN = C('TOKEN');
////       session_destroy();
//        $utils = new WeChatUtils($APPID, $APPSECRET, $TOKEN);
//        if (!isset($_GET['code'])) {
//            //如果没有收到CODE返回值，就发送请求
//            $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
//            $utils->getUserCodeByUrl('',$baseUrl);
//        }else{
//            $code = $_GET['code'];
//            $result = $utils->getHtmlAccessToken($code);
//            $userInfo = $utils->getUserInfo($result->access_token,$result->openid);
//            $logic = new UserLogic();
//            $user = $logic->saveOrUpdateUser($result->openid,$userInfo);
//            session('user',$user);//存入sessoin
//        }
//        $this->display();
//    }

    public function new_index(){
        $this->display();
    }

    /**
     * ajax添加充值记录
     */
    public function addRechargeLog(){
        $money = I('money');
        if(!is_numeric($money) && $money <=0){
            $this->ajax(false,'请填写正确的金额!');
        }
        $user = cookie('user');
        if(empty($user['id'])){
            $this->ajax(false,'请重新登录!');
        }
        if(empty($user['phone'])){
            $this->ajax(false,'请先绑定手机号!');
        }
        $logic = new PayLogic();
        $order_id = $logic->addRechargeLog($money,$user['id']);
//        $order_id = 1;
        if($order_id){
//            $url = 'http://'.$_SERVER['HTTP_HOST'].'/Home/Recharge/Pay?order_id='.$order_id;
            $order = M('RechargeOrder')->where(array('id'=>$order_id))->find();
            $system_name = $this->getSystemName();
            $result = $this->makeKuaiJiePay( $system_name.'充值','充值', $order['order_number'], $order['money']);
            if($result['status'] != 1){
                $this->ajax(false,$result['msg']);
            }else {
                $this->ajax(true, '添加订单成功!', -1, array('url' => $result['pay_url']));
            }
        }else{
            $this->ajax(false,'添加订单失败!');
        }
    }

    protected function ajax($success,$message,$code=-1,$data=array()){
        $this->ajaxReturn(array(Constants::SUCCESS=>$success,Constants::MESSAGE=>$message,'data'=>$data,'code'=>$code));
    }

    public function pay(){
        $order_id = I('order_id');
        $order = D('RechargeOrder')->where(array('id'=>$order_id))->find();
        if($order){
            $openid = D('user')->where(array('id'=>$order['user_id']))->getField('openid');
            $system_name = $this->getSystemName();
            $this->makeWeChatPay($openid, $system_name.'充值','充值', $order['order_number'], $order['money']);
            $this->assign('success',true);
            $this->assign('recharge','1');
            $this->display('pay');
        }else{
            //跳转到首页
            $this->redirect('/Home/Index/index');
        }
    }

    public function weChatPayRtn(){
        //初始化日志
        if (!is_dir('./logs/')) {
            mkdir('./logs/', 0755, true);
        }
        echo 'weChatPayRtn';
        $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);
        $notify = new PayNotifyCallBack();
        $log->DEBUG('begin notify');
        $notify->Handle(true);
    }

    /**
     * 构造微信支付页面
     * @param $openid
     * @param $description
     * @param $title
     * @param $order_number
     * @param $money
     * @throws \WxPayException
     */
    private function makeWeChatPay($openid,$description, $title, $order_number, $money)
    {
        vendor('WxPay');
        vendor('Wxpay.WxPay_JsApiPay');
        vendor('Wxpay.WxPay_Api.php');
        $tools = new \JsApiPay();
        $openId = $openid;
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $description =mb_substr($description,0,20,'utf-8');
        $title =mb_substr($title,0,10,'utf-8');
        $input->SetBody($description);
        $input->SetAttach("test");
        $input->SetOut_trade_no($order_number);
        $input->SetTotal_fee($money*100);
//        $input->SetTotal_fee(1);
//        $input->SetTotal_fee($money);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($title);
        $url = 'http://'.$_SERVER['HTTP_HOST']."/Home/Recharge/weChatPayRtn";
        $input->SetNotify_url($url);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);

        //获取共享收货地址js函数参数
        $editAddress = $tools->GetEditAddressParameters();
        $this->assign('jsApiParameters', $jsApiParameters);
        $this->assign('editAddress', $editAddress);
        $this->assign('money', $money);
    }

    public function pay_image(){
        $money = I('money');
        $this->assign('money',$money);
        $this->display();
    }

    public function kuaiJiePay(){
        $order_id = I('order_id');
        $order = D('RechargeOrder')->where(array('id'=>$order_id))->find();
        if($order){
            $openid = D('user')->where(array('id'=>$order['user_id']))->getField('openid');
            $system_name = $this->getSystemName();
            $this->makeWeChatPay($openid, $system_name.'充值','充值', $order['order_number'], $order['money']);
            $this->assign('success',true);
            $this->assign('recharge','1');
            $this->display('kuai_jie_pay');
        }else{
            //跳转到首页
            $this->redirect('/Home/Index/index');
        }
    }

    private function makeKuaiJiePay($description, $title, $order_number, $money){
        $data['merchant_no'] = '2018937859';//商户号
        $data['merchant_order_no'] = $order_number;//订单号
        $url = 'http://'.$_SERVER['HTTP_HOST']."/Home/Recharge/kuaiJieReturn";
        $data['notify_url'] = $url;//订单号
        $data['start_time'] = date('ymdHis',time());
        $data['trade_amount'] = $money;
//        $data['trade_amount'] = 1;
        $data['goods_name'] = $title;
        $data['goods_desc'] = $description;
//        $data['app_no'] = '201805171459095201';
        $data['return_url'] = 'http://'.$_SERVER['HTTP_HOST']."/Home/Me/index";
        $data['sign_type'] = "1";
        $sort_array = $this->paraFilters($data);
        $sort_array = $this->argSorts($sort_array);
        $data['sign'] = $this->sign($sort_array,'ff64bab6683d1e6dbcf60b67eea64bab');
        $send_url = 'http://api.kj-pay.com/wechar/public_pay';
        $http_utils = new HttpUtils();
        $result = $http_utils->httpPost($send_url,$data);
        $result_obj = json_decode($result);
        $result = (array)$result_obj;
        if(isset($result['data'])){
            $result['data'] = (array)$result['data'];
        }
        if(!$result){
            return ['status'=>0, 'msg'=>'支付失败'];
        }else{
            if($result['status'] !=1){
                return ['status'=>0,'msg'=>'支付失败,'.$result['info']];
            }else{
                return ['status'=>1,'pay_url'=>$result['data']['pay_url']];
            }
        }
    }

    /**
     * 快接支付回调
     */
    public function kuaiJieReturn(){
        $data['status'] = I('status');
        $data['msg'] = I('msg');
        $data['amount'] = I('amount');
        $data['merchant_order_no'] = I('merchant_order_no');
        $data['trade_no'] = I('trade_no');
        $data['payment_time'] = I('payment_time');
        $data['pay_channel'] = I('pay_channel');
        $data['pay_channel_name'] = I('pay_channel_name');
        $sort_array = $this->paraFilters($data);
        $sort_array = $this->argSorts($sort_array);
        $sign = $this->sign($sort_array,'ff64bab6683d1e6dbcf60b67eea64bab');
        $data['sign'] = I('sign');
        if($sign == $data['sign']){
            $money = $data['amount'];
            $logic = new PayLogic();
            $success = $logic->weChatPaySuccess($data['merchant_order_no'],$money,0);
            if($success == 1){
                echo "success";
                exit;
            }else{
            }
        }
    }

    /**
     * 除去数组中的空值和签名参数
     * @param $para array 签名参数组
     * @return mixed 去掉空值与签名参数后的新签名参数组
     */
    private function paraFilters($para) {
        $para_filter = array();
        while (list ($key, $val) = each ($para)) {
            if($key == "sign" || $val == "")continue;
            else	$para_filter[$key] = $para[$key];
        }
        return $para_filter;
    }

    /**
     * 对数组排序
     * @param $para array 排序前的数组
     * @return mixed 排序后的数组
     */
    private function argSorts($para) {
        ksort($para);
        reset($para);
        return $para;
    }

    /**
     * 签名验证-快接支付
     * @param $datas array 数据数组
     * @param $key string 密钥
     * @return mixed
     */
    private  function sign($datas = array(), $key = ""){
        $str = urldecode(http_build_query($this->argSorts($this->paraFilters($datas))));
        $sign = md5($str."&key=".$key);
        return $sign;
    }

    public function kuaiJiePayTest(){
        $order = M('RechargeOrder')->where(array('id'=>3772))->find();
        $system_name = $this->getSystemName();
        $this->makeKuaiJiePay( $system_name.'充值','充值', $order['order_number'], $order['money']);
    }
}
vendor('WxPay');
vendor('Wxpay.WxPay_Notify');
vendor('Wxpay.WxPay_Api');
vendor('Wxpay.log');
class PayNotifyCallBack extends \WxPayNotify
{
    //查询订单
    public function Queryorder($transaction_id)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input);
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            return true;
        }
        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {
        $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);
        $notfiyOutput = array();
        if(!array_key_exists("transaction_id", $data)){
            $msg = "输入参数不正确";
            $log->DEBUG($msg);
            return false;
        }
        //查询订单，判断订单真实性
        if(!$this->Queryorder($data["transaction_id"])){
            $msg = "订单查询失败";
            $log->DEBUG($msg);
            return false;
        }
        $money = $data['total_fee'];
        $logic = new PayLogic();
        $success = $logic->weChatPaySuccess($data['out_trade_no'],$money,0);
        $log->DEBUG('success:'.$success);
        $log->DEBUG('out_trade_no:'.$data['out_trade_no']);
        if($success == 1){
            return true;
        }else{
            return false;
        }
        return true;
    }
}